package cn.xmall.services.cn.xmall.services.impl;

import cn.xmall.caches.OrderCache;
import cn.xmall.commons.models.PageQueryResult;
import cn.xmall.mappers.OrderMapper;
import cn.xmall.models.*;
import cn.xmall.services.ItemOrderService;
import cn.xmall.vo.OrderStatuEnum;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.Date;
import java.util.List;

/**
 * Created by MoTaiXian on 2017/7/20.
 */
@Service
public class ItemOrderServiceImpl implements ItemOrderService {
    private static final Logger logger = LoggerFactory.getLogger(ItemOrderServiceImpl.class);

    @Autowired
    OrderCache orderCache;

    @Autowired
    OrderMapper orderMapper;

    final  String itemOrderPrefix="P";

    @Override
    public PageQueryResult<Order> getListByUserWithPage(User user, int page, int rowNum){
        try {
            Assert.notNull(user, "illegal userSessionId");
            Assert.notNull(user.getId(), "illegal user id");

            OrderExample orderExample = new OrderExample();
            OrderExample.Criteria criteria = orderExample.createCriteria();
            criteria.andUserIdEqualTo(user.getId());

            PageHelper.startPage(page,rowNum);
            List<Order> orderList=orderMapper.selectByExample(orderExample);

            PageInfo<Order> pageInfo = new PageInfo<>(orderList);
            PageQueryResult pageQueryResult=new PageQueryResult();
            pageQueryResult.setTotal(pageInfo.getTotal());
            pageQueryResult.setRows(orderList);

            return pageQueryResult;
        }catch (Exception e){
            return null;
        }
    }
    // TODO: 2017/7/21  需捕捉订单号重复异常在尾缀添加相应字母或数字
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void create(Order order) {
        //填充订单ID
        String orderId=orderCache.generateUniqueOrderId(itemOrderPrefix,"");
        order.setOrderId(orderId);
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        orderMapper.insert(order);
    }

    @Override
    @Transactional
    public void UpdateStatuById(User currentUser,String orderId, OrderStatuEnum orderStatu){
        Assert.notNull(orderId,"orderId is null");
        OrderExample orderExample=new OrderExample();
        OrderExample.Criteria criteria=orderExample.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        criteria.andUserIdEqualTo(currentUser.getId());
        Order temp_order=new Order();
        temp_order.setStatus(orderStatu.getCode());
        orderMapper.updateByExampleSelective(temp_order,orderExample);
    }

}
